package springjunit.services;

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.internal.SessionFactoryImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(loader = AnnotationConfigWebApplicationContextLoader.class)
@ContextConfiguration(locations = { "classpath:/spring/*.xml" })
public abstract class ServiceTestBase {
	@Autowired
    protected ApplicationContext context;
    private Connection connection;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }


    @Before
    public void setup() throws SQLException {
    }

    protected Connection getConnection() throws SQLException{
    	if(this.connection==null || connection.isClosed()){
    		SessionFactoryImpl factory = (SessionFactoryImpl) context.getBean("sessionFactory");
        	connection = factory.getConnectionProvider().getConnection();
    	}
    	return connection;
    }
    
    @After
    public void tearDown(){
    	if(this.connection!=null){
    		try {
				this.connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
    	}
    }
    
    protected String getTestDataPath(){
    	return "./src/test/resources/testdata/";
    }
}
